package core;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 交互式Socket连接
 *
 */
public class InteractSocket extends Socket {

	//交互流数据默认编码
	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
	
	//交互流数据编码
	private Charset charset = DEFAULT_CHARSET;
	
	public InteractSocket(String host, int port) throws UnknownHostException, IOException {
		super(host, port);
	}
	
	public InteractSocket(String host, int port,Charset charset) throws UnknownHostException, IOException {
		super(host, port);
		this.charset = charset;
	}
	
	/**
	 * 发送命令并读取响应
	 * @param cmd　命令
	 * @return　命令响应
	 * @throws IOException　soket流读写异常
	 */
	public String sendCommand(String cmd) throws IOException {
		if(!this.isConnected()) return null;
		
		if(cmd==null||"".equals(cmd.trim())) return null;
		//命令如果没有换行符则补充一个
		if(!cmd.endsWith("\n")) {
			cmd+="\n";
		}
		
		/*
		 * 将命令写入Socket
		 */
		OutputStream output = this.getOutputStream();
		output.write(cmd.getBytes(this.charset));
		
		try {
			//休息一下，等待数据
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		/*
		 * 从Socket读取响应
		 */
		StringBuilder builder = new StringBuilder(); 
		InputStreamReader input = new InputStreamReader(this.getInputStream(),this.charset);
		char[] chareBuf = new char[1024];
		int len;
		while((len=input.read(chareBuf))!=-1) {
			builder.append(chareBuf,0,len);
			if(len<chareBuf.length) {
				break;
			}
		}
		return builder.toString();
	}
}
